import cv2  # opencv读取的格式是BGR
import matplotlib.pyplot as plt
import numpy as np

def show(name, img):
    cv2.imshow(name, img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

img = cv2.imread('demo.png')
# show('img', img)
ratio = img.shape[0] / 500.0
orig = img.copy()

img = cv2.resize(img, (500, int((500 * img.shape[0])/img.shape[1])))
# 预处理
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
# 边缘检测
edged = cv2.Canny(gray, 75, 200)
# show('edged', edged)
# 轮廓处理
cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:5]  # reverse=True表示倒序(从大到小)
show('img', img)
